function isMobile() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

function addTapListener(element: any, callback: any) {
  let startX: number, startY: number, startTime: number;
  const maxMove = 10; // 最大允许移动距离(px)
  const maxDuration = 300; // 最长允许持续时间(ms)

  element.addEventListener(
    "touchstart",
    function (e: any) {
      startX = e.touches[0].clientX;
      startY = e.touches[0].clientY;
      startTime = Date.now();
    },
    { passive: true }
  );

  element.addEventListener(
    "touchend",
    function (e: any) {
      if (!startTime) return;

      const endX = e.changedTouches[0].clientX;
      const endY = e.changedTouches[0].clientY;
      const duration = Date.now() - startTime;

      // 判断是否满足tap条件
      if (Math.abs(endX - startX) < maxMove && Math.abs(endY - startY) < maxMove && duration < maxDuration) {
        callback(e);
      }

      startTime = 0; // 重置状态
    },
    { passive: true }
  );
}

export default {
  install(app: any) {
    app.directive("route", {
      mounted: (el: any, binding: any) => {
        el.style.cursor = "pointer";
        if (isMobile()) {
          addTapListener(el, () => {
            binding.instance.$router.push({ name: binding.value });
          });
        } else {
          el.addEventListener("click", () => {
            binding.instance.$router.push({ name: binding.value });
          });
        }
      },
    });
  },
};
